<script>
export default {
    data() {
        return {
            websock: null,
            url: '',
        }
    },
    destroyed() {
        this.websock.close() //离开路由之后断开websocket连接
    },
    methods: {
        initWebSocket(url,websocketonmessage) { //初始化weosocket
            this.url = url;
            let wsuri = this.url;
            this.websock = new WebSocket(wsuri);
            this.websock.onmessage = websocketonmessage;
            this.websock.onopen = this.websocketonopen;
            this.websock.onerror = this.websocketonerror;
            this.websock.onclose = this.websocketclose;
        },
        websocketonopen() { //连接建立之后执行send方法发送数据
            /*let actions = {"test":"12345"};
            this.websocketsend(JSON.stringify(actions));*/
        },
        websocketonerror() {//连接建立失败重连
            this.initWebSocket(this.url);
        },
        /*websocketonmessage(e) { //数据接收
            const redata = e.data;
            console.log(redata);

        },*/
        websocketsend(Data) {//数据发送
            this.websock.send(Data);
        },
        websocketclose(e) {  //关闭
            console.log('断开连接', e);
        },
    },
}
</script>
<style lang='less'>

</style>
